#!/usr/bin/env python
from lib.format_time import *
from lib.HandleMysql import *
from lib.switch_code import *
from shop_conn import *
import json
import sys
import re
reload(sys)
sys.setdefaultencoding('utf-8')

def get_product_info_visit_data(date):
    
    print "get_product_info_visit_data bigin : %s"%date
    stat_conn = set_stats_conn()
    prod_conn = set_product_conn()
    conn = set_order_conn()
    stat_table = "product_info_visit_stats"
    
    #get data
    query = "select product_id,pv,visits,uv,new_visits,new_uv from product_flux_day where product_id > 0 and stat_date='%s' "%date 
    #print query
    items = stat_conn.get_results(query)
    for item in items:        
        product_id = item[0]
        pv = item[1]
        visits = item[2]
        uv = item[3]
        new_visits = item[4]
        new_uv = item[5]
        
        #print product_id
        query_in = "select cateid,local,param,shopid from t_product where productid=%s"%product_id
        items_in = prod_conn.get_results(query_in)
        #print query_in
        if len(items_in) == 0:
            continue        
        
        cate_id = items_in[0][0]
        local =items_in[0][1]
        param = items_in[0][2]
        shop_id = items_in[0][3]
        
        #print cate_id
        dc = get_thirth_cat(cate_id,param)    
        cat1 = 0
        cat1name = ''
        cat2 = 0
        cat2name=''
        cat3 = 0
        cat3name=''
        if dc != None:
            cat1 = dc[0][0]
            cat1name = dc[0][1]
            if len(dc) > 1:
                cat2 = dc[1][0]
                cat2name=dc[1][1]
            if len(dc) > 2:
                cat3 = dc[2][0]
                cat3name=dc[2][1]
        city_id = 0
        city_name =''
        if local != None and local !='':
            city = json.loads(local)[0]['L']        
            city_id,city_name = get_citys(city)
        
        shop_type = 0
        query_in = "select shop_type from shop_info where shop_id=%s"%shop_id
        items_in = stat_conn.get_results(query_in)
        if len(items_in) > 0:
            shop_type = items_in[0][0]
            
        #order count
        #query_in = "select count(1),ifnull(sum(fee),0),ifnull(sum(pcount),0) from (select COUNT(DISTINCT b.orderid) as ocount,a.ordertotal as fee,sum(b.num) as pcount from t_order a left join  t_orderproduct b on a.orderid=b.orderid where a.refer<>4 and a.state>2 and date(a.createdate)='2012-11-29' and b.productid=11449018518017 group by a.orderid) a;"(date,product_id)
        #items_in = stat_conn.get_results(query_in)
        #pay_order_count = items_in[0][0]
        #pay_amount = items_in[0][1]
        #product_count = items_in[0][2]

        pay_order_count = 0
        pay_amount = 0
        product_count = 0
        
        param = [date,product_id,shop_id,cat1,cat1name, cat2,cat2name,cat3,cat3name,city_id,city_name,pv,visits,uv,new_visits,new_uv,shop_type,cate_id,pay_order_count,pay_amount,product_count]
        stat_conn.insert_record(stat_table,param)
    
    stat_conn.close()
    prod_conn.close()
    conn.close()
    print "get_product_info_visit_data end : %s"%date

def get_second_cat(cate_id ):
    stat_conn = set_stats_conn()
    query = 'select fullpath from t_dispcategory where cateid =%s and depth=1;' % (cate_id)
    #print query
    items = stat_conn.get_results(query)
    if len(items) == 0:
        q = "select cateid, catename from t_category where cateid=%s" % cate_id
        rt = stat_conn.get_results(q)
        return rt
    
    fullpath = items[0][0]        
    q = "select dispcategoryid, catename from t_dispcategory where dispcategoryid in (%s) order by depth asc" % fullpath
    rt = stat_conn.get_results(q)
    
    stat_conn.close()
    return rt

def get_thirth_cat(cate_id ,param):    
    stat_conn = set_stats_conn()
    query = 'select param_id from t_cate_param where cate_id = %s;' % cate_id
    items = stat_conn.get_results(query)
    if len(items) == 0:
        return get_second_cat(cate_id )
    param_id = items[0][0]
    reg = '{"I":%s,"V":"(\w*)"}'%param_id
    #print reg
    pattern =  re.compile(reg)
    matchs = pattern.search(param)
    #print reg
    objval = "0"
    #print matchs
    try:
        objval = matchs.group(1)
    except Exception,e:
        return get_second_cat(cate_id )
        
    filter_str = "objecttype=%s"%objval
    #print filter_str
    query = "select fullpath from t_dispcategory where cateid =%s and filter='%s'" % (cate_id,filter_str)
    items = stat_conn.get_results(query)
    if len(items) == 0:
        return get_second_cat(cate_id )
    fullpath = items[0][0]      
    q = "select dispcategoryid, catename from t_dispcategory where dispcategoryid in (%s) order by depth asc" % fullpath
    rt = stat_conn.get_results(q)
    
    stat_conn.close()
    
    return rt
def get_citys(city):
    if city == 0 :
        return 0,''
    
    stat_conn = set_stats_conn()
    q = 'select depth,fullpath,localid,localname from t_local where localid=%s' % city
    items = stat_conn.get_results(q)
    if len(items) == 0:
        return 0,''
    depth = items[0][0]
    if depth == 0:
        return items[0][2],items[0][3]
    
    fullpath = items[0][1]
    q = "select localid, localname from t_local where localid in (%s) order by depth asc limit 1" % fullpath
    #print q
    rt = stat_conn.get_results(q)
    if len(rt) == 0:
        return 0,''
    
    return rt[0][0],rt[0][1]
#logic
def execute(date):
    # get main data
    # from order orderproduct orderticket orderpay orderlog
    get_product_info_visit_data(date)
   # pass
def main():

   #date = '2012-05-28'
   #execute(date)   
   if len(sys.argv)==1:
        start_date=get_yesterday()
        end_date=start_date
   elif len(sys.argv)==2:
        start_date=format_date(sys.argv[1])
        end_date=start_date
   elif len(sys.argv)==3:
        start_date=format_date(sys.argv[1])
        end_date=format_date(sys.argv[2])
   stat_date=start_date
   while stat_date>=start_date and stat_date<=end_date:
        print "The program of the date of %s is beginning at %s " %(stat_date,get_now())
        #
        execute( stat_date) 
        print "The program of the date of %s is end at %s " %(stat_date,get_now())
        stat_date=var_date(stat_date)


if __name__=='__main__':
    main()

